import { hasToken, setLocalChannels, getLocalChannels } from './../../utils/storage';
import {
  addUserChannelsAPI,
  delUserChannelsAPI,
  getAllChannelsAPI,
  getUserChannelsAPI,
} from '@/api/channel';
import { Toast } from 'antd-mobile';
import store, { AppDispatch } from '..';
import { ActionType, ChannelType } from '../reducer/channel';

export const getAllChannelsAction = () => {
  return async (disaptch: AppDispatch) => {
    const res = await getAllChannelsAPI();
    disaptch({ type: 'channel/saveAllChannel', payload: res.data.channels });
  };
};

export const getUserChannelsAction = () => {
  return async (disaptch: AppDispatch) => {
    if (hasToken()) {
      const res = await getUserChannelsAPI();
      disaptch({ type: 'channel/saveUserChannel', payload: res.data.channels });
      return;
    }

    const localUserChannels = getLocalChannels();
    if (localUserChannels.length) {
      disaptch({ type: 'channel/saveUserChannel', payload: localUserChannels });
      return;
    }
    const res = await getAllChannelsAPI();
    const userList = res.data.channels.slice(0, 11);
    disaptch({ type: 'channel/saveUserChannel', payload: userList });
    setLocalChannels(userList);
  };
};

export const addUserChannelsAction = (newChannel: ChannelType) => {
  return async (disaptch: AppDispatch) => {
    if (hasToken()) {
      await addUserChannelsAPI(newChannel);
    } else {
      setLocalChannels([...getLocalChannels(), newChannel]);
    }
    Toast.show({ content: '更新成功' });
    disaptch({ type: 'channel/addUserChannel', payload: newChannel.id });
  };
};

export const delUserChannelsAction = (id: number) => {
  return async (disaptch: AppDispatch, getState: typeof store.getState) => {
    if (id === 0) {
      Toast.show({ content: '不能删除推荐频道' });
      return;
    }

    const { userChannels } = getState().channel;
    if (userChannels.length <= 5) {
      Toast.show({ content: '至少保留5个频道' });
      return;
    }

    if (hasToken()) {
      await delUserChannelsAPI(id);
    } else {
      const newList = getLocalChannels().filter((item) => item.id !== id);
      setLocalChannels(newList);
    }
    Toast.show({ content: '更新成功' });
    disaptch({ type: 'channel/delUserChannel', payload: id });
  };
};

export const setCurrentAction = (id: number): ActionType => ({
  type: 'channel/setCurrentId',
  payload: id,
});
